package com.ericsson.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ericsson.web.core.Constants;
import com.ericsson.web.core.HSQLDatabase;
import com.ericsson.web.core.IDatabase;
import com.ericsson.web.core.Utils;

public class Logout extends HttpServlet {
	
	private final static String REMEMBER_ME="rememberme";
	private final static String SERIES_ID="sid";
	private final static String TOKEN="token";
	
	private static <T> T getFromSession(HttpSession session, String name, T dValue) {
		T result = dValue;
		Object value = session.getAttribute(name);
		if(value != null) {
			result = (T)value;
		}
		return result;
	}
	
	@Override
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) 
	throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		if(session != null) {
			if(getFromSession(session, REMEMBER_ME, "false").equals("true")) {
				int userId = getFromSession(session, Constants.USERID, -1);
				String sid = getFromSession(session, SERIES_ID, null);
				if(userId >= 0 && !Utils.isEmpty(sid)) {
					IDatabase db = HSQLDatabase.getInstance();
					db.removeSession(userId, sid);
				}
			}
			removeCookie(response, REMEMBER_ME);
			removeCookie(response, SERIES_ID);
			removeCookie(response, TOKEN);
			
			session.setAttribute(Constants.USERID, -1);
		}
		response.sendRedirect(Constants.LOGIN_PAGE);
	}
	
	private void removeCookie(HttpServletResponse response, String name) {
		Cookie cookie = new Cookie(name, "");
		cookie.setMaxAge(0);
		cookie.setPath(Constants.URL_ROOT);
		response.addCookie(cookie);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, 
			HttpServletResponse response) 
	throws ServletException, IOException {
		doGet(request, response);
	}
}
